package com.file.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class JsonUtils {
	
	private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
	
    /**
     * serialize a class instance to Json String.
     *
     * @param object the class instance to serialize
     * @param <T> the type of the element
     * @return JSON String
     */
    public static <T> String convertObjectToJson(T object) {
        Writer write = new StringWriter();
        try {
            OBJECT_MAPPER.writeValue(write, object);
        } catch (Exception e) {
            log.error("[OnError]convertObjectToJson failed", e);
            throw new RuntimeException(e);
        } 
        return write.toString();
    }
    
    public static <T> List<T> convertJsonToObjectList(String json) {
    	List<T> tList = null;
    	
    	try {
			tList = OBJECT_MAPPER.readValue(json, new TypeReference<ArrayList<T>>(){});
		} catch (Exception e) {
			log.error("[OnError]convertJsonToObjectList failed", e);
            throw new RuntimeException(e);
		} 
    	
    	return tList;
    }
    
    public static <T> T convertJsonToObject(String json, Class<T> clazz) {
    	T t = null;
    	try {
			t = OBJECT_MAPPER.readValue(json, clazz);
		} catch (Exception e) {
			log.error("[OnError]convertJsonToObject failed", e);
            throw new RuntimeException(e);
		}
    	return t;
    }
   
//    public static void main(String[] args) {
//    	String x = "{\r\n"
//    			+ "    \"msg\": \"系统处理成功\",\r\n"
//    			+ "    \"replyTime\": \"2021-06-17 19:15:04\",\r\n"
//    			+ "    \"code\": \"60840000\",\r\n"
//    			+ "    \"jsonData\": \"{\\\"tickets\\\":[{\\\"value\\\":\\\"37d87b21ccc0e7ec824f05be0c0f59d19871819e70ba2852e03449a18dbc29c2\\\",\\\"expire_time\\\":\\\"1623932104000\\\",\\\"expire_in\\\":3600}]}\",\r\n"
//    			+ "    \"bizSeqNo\": \"2106170FD06542191504451036274098\",\r\n"
//    			+ "    \"version\": \"3.0.0\"\r\n"
//    			+ "}";
//    	System.out.println(convertJsonToObject(x, GetWldSignTicketResponseDTO.class));
//    }

}
